package com.example.gulimall.product.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.gulimall.product.entity.CategoryEntity;
import com.example.gulimall.product.service.CategoryService;
import com.example.gulimall.product.vo.Catelog2Vo;
import com.sun.javafx.collections.MappingChange;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //配置路由规则 访问这三个都可以请求到
    //查询所有一级菜单
    @GetMapping({"/", "/index.html", "index"})
    public String Index(Model model) {
        List<CategoryEntity> categorys = categoryService.getLevel1Categorys();
        model.addAttribute("categories",categorys);
        //试图解析器进行拼串 classpath/templates/* .html
        return "index";
    }
    //查询菜单层级关系。让页面生成层级列表
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCataLogJson() throws InterruptedException {

        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCataLogJson();
        return catalogJson;
    }
    @ResponseBody
    @GetMapping("/hello")
    public  String hello(){
        //1 获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
        //2 加索
       // lock.lock(); //阻塞式等待，如果加不到锁，一直等
        lock.lock(10, TimeUnit.SECONDS);//10秒后自动解锁
        //锁的自动续期，如果业务超长，运行期间自动给锁续上新的30秒，默认加30秒，不用担心业务时间过长，锁自动过期
        // 加索的业务只要运行完成，就不会给当前锁续期，也不会存在死锁问题，即使不手动解锁，也会在30秒后解锁
        try {
            System.out.println("加索成功,执行业务。。。"+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){
        }finally {
            System.out.println("释放锁。。。。"+Thread.currentThread().getId());
            //解锁 假设解锁代码没有运行，redisson会不会出现死锁，即使我们没有手动解锁也不会有死锁问题
            //看门狗事件，可以自动续期
            lock.unlock();
        }
        return  "hello";

    }

    @GetMapping("/write")
    @ResponseBody
    public  String write(){
        String s="";
        //获取一把锁，只要锁的名字一样，就是同一把锁
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        //获取写锁
        RLock rLock = lock.writeLock();
        try {
            // 1 加锁 改数据，加写锁
            rLock.lock();
            System.out.println("写锁加锁成功。。。。"+Thread.currentThread().getId());
            s=UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue",s);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("写锁释放成功。。。。"+Thread.currentThread().getId());
        }
        return s;
    }
    @GetMapping("/read")
    @ResponseBody
    public  String read() throws InterruptedException {
        String s="";
       //获取一把锁，只要锁的名字一样，就是同一把锁

        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        //获取读锁
        RLock rLock = lock.readLock();

        try {
            //加读锁
            rLock.lock();
            System.out.println("读锁加锁成功。。。。"+Thread.currentThread().getId());
            Thread.sleep(30000);
            // 2 读数据，加读锁
             s = stringRedisTemplate.opsForValue().get("writeValue");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("读锁释放成功。。。。"+Thread.currentThread().getId());
        }
        return s;
    }
    /**
     * 车库停车
     * 3个车位
     */
    @GetMapping("/park")
    @ResponseBody
    public  String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.acquire();
        return "ok";
    }
    @GetMapping("/gogo")
    @ResponseBody
    public  String gogo() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();

        return "ok";
    }
    /**
     * 学校放假锁门，必须所有班级走完，才能锁校门
     * 现在有5个班
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public  String lockDoor() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);//设置总共有多少
        door.await();//等待闭锁完成

        return  "放假了。。。。。";
    }
    @GetMapping("/go/{id}")
    @ResponseBody
    public String go(@PathVariable("id") Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();//计数减1
        return  id+"班的人走了";
    }
}
